#!/bin/bash
# tools to run dmctl from command line
# parameter 1: work directory
# parameter 2: master-addr port
# parameter 3: command
# parameter 4...: check output content and count

workdir=$1
master_addr=$2
cmd=$3

shift 3

PWD=$(pwd)
binary=$PWD/bin/dmctl.test
ts=$(date +"%s")
dmctl_log=$workdir/dmctl.$ts.log
pid=$$

echo "dmctl test cmd: \"$cmd\""


all_matched=true
for ((k=0; k<10; k++)); do
    echo "$cmd" | $binary -test.coverprofile="$TEST_DIR/cov.$TEST_NAME.dmctl.$ts.$pid.out" DEVEL -master-addr=$master_addr > $dmctl_log 2>&1
    all_matched=true
    for ((i=1; i<$#; i+=2)); do
        j=$((i+1))
        value=${!i}
        expected=${!j}
        got=$(sed "s/$value/$value\n/g" $dmctl_log | grep -c "$value")
        if [ "$got" != "$expected" ]; then
            echo "command: $cmd $value count: $got != expected: $expected, failed the $k-th time, will retry again"
            all_matched=false
            break
        fi
    done
    
    if $all_matched; then
        exit 0
    fi

    sleep 2
done

cat $dmctl_log
exit 1